package com.ibl.rover.lite.client.Activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import com.ibl.rover.lite.client.Logger;
import com.ibl.rover.lite.client.R;
import com.ibl.rover.lite.client.Application.ApplicationContext;
import com.ibl.rover.lite.client.Application.OrderBookingLine;
import com.ibl.rover.lite.client.constants.RoverConstants;
import com.ibl.rover.lite.common.bean.OrderBean;
import com.ibl.rover.lite.common.bean.ProductBean;
import com.ibl.rover.lite.common.bean.ProductCategroy;
import com.ibl.rover.lite.common.db.Criteria;
import com.ibl.rover.lite.common.db.DatabaseManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.NumberKeyListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewParent;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TableRow.LayoutParams;

public class SalesBookingActivity extends Activity implements OnClickListener {

	Logger logger = new Logger();
	private ApplicationContext roverApp;
	private Spinner skuSpinner;
	private DatabaseManager manager = null;
	private OrderBookingLine orderBookingLine;
	private OnKeyListener keyListener = null;
	private CheckBoxClickListener listener = new CheckBoxClickListener();
	private NumberKeyListener numberKeyListner;
	ProgressDialog progressDlg = null;
	final Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.sales_booking);
			roverApp = (ApplicationContext) getApplication();
			manager = roverApp.getDatabaseManager();
			initialize();
		} catch (Exception e) {
			logger.logException("onCreate Exception ", e);

		}
	}

	/**
	 * 
	 * Initialize Resources
	 */
	private void initialize() {
		try {

			skuSpinner = (Spinner) findViewById(R.id.sku_spinner);

			ArrayAdapter<CharSequence> routeAdapter = new ArrayAdapter<CharSequence>(
					this, android.R.layout.simple_spinner_item,
					roverApp.getSkuTypes());

			routeAdapter
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			skuSpinner.setAdapter(routeAdapter);

			((Button) findViewById(R.id.searchProduct))
					.setOnClickListener(this);

			((Button) findViewById(R.id.save_order)).setOnClickListener(this);
			numberKeyListner = new NumberKeyListener() {
				@Override
				protected char[] getAcceptedChars() {
					char[] numberChars = { '1', '2', '3', '4', '5', '6', '7',
							'8', '9', '0' };

					return numberChars;
				}

				@Override
				public int getInputType() {
					return 0;
				}
			};

			keyListener = new OnKeyListener() {
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					switch (event.getAction()) {
					case KeyEvent.ACTION_UP:
						calculatePrice();
						break;

					}
					return false;
				}
			};

			if (roverApp.getViewContext().containsKey(
					RoverConstants.CURRENT_PREVIOUS_ORDER_SUCESS_BOOKIG_LINE)) {
				orderBookingLine = (OrderBookingLine) roverApp
						.getViewContext()
						.get(RoverConstants.CURRENT_PREVIOUS_ORDER_SUCESS_BOOKIG_LINE);
			} else {
				orderBookingLine = new OrderBookingLine();
			}

			if (orderBookingLine.getProductBeanList() == null) {
				orderBookingLine
						.setProductBeanList(new ArrayList<ProductBean>());
				orderBookingLine
						.setProductQuantitylist(new ArrayList<String>());
			} else {
				buildProductsTable(orderBookingLine);
			}

		} catch (Exception e) {
			logger.logException("Intialize Exception :	", e);
		}

	}

	/**
	 * Calculate Price
	 */
	private void calculatePrice() {
		try {
			TableLayout tableLayout = (TableLayout) findViewById(R.id.sales_table);

			TableRow row;
			double totalPrice = 0.0, price = 0.0;
			EditText quantityText;

			for (int i = 1; i < tableLayout.getChildCount(); i++) {
				row = (TableRow) tableLayout.getChildAt(i);
				int index = orderBookingLine.getProductBeanList().indexOf(
						row.getTag());
				quantityText = (EditText) row.getChildAt(2);
				price = Double.parseDouble(((TextView) row.getChildAt(1))
						.getText().toString());
				orderBookingLine.getProductQuantitylist().set(index,
						quantityText.getText().toString());

				totalPrice += price
						* Integer.parseInt(quantityText.getText().toString());

			}
			 
			
			((TextView) findViewById(R.id.total_price)).setText(String
					.valueOf(Math.round(totalPrice)));

		} catch (Exception e) {
			logger.logException("Calculate Price", e);
		}

	}

	@Override
	public void onClick(View view) {
		try {
			switch (view.getId()) {
			case R.id.searchProduct:
//				doSearchProduct();
				searchProduct();
				break;

			case R.id.save_order:
				saveOrder();
				break;

			default:
				break;
			}
		} catch (Exception e) {
			logger.logException("onClick Exception :", e);
		}

	}

	private void saveOrder() {
		try {
			calculatePrice();
			if (isQuantityFilled()) {
				orderBookingLine
						.setOrderAmount(((TextView) findViewById(R.id.total_price))
								.getText().toString());
				roverApp.getViewContext().put(
						RoverConstants.CURRENT_ORDER_BOOKING_LINE,
						orderBookingLine);

				Intent intent = new Intent(this, OrderDetailActivity.class);
				startActivity(intent);
			} else {
				roverApp.showMessage(
						"Please Enter the Quantity of All Product",
						Toast.LENGTH_LONG);
			}
		} catch (Exception e) {
			logger.logException("Save order Eception", e);
		}
	}

	private boolean isQuantityFilled() {
		try {
			TableLayout tableLayout = (TableLayout) findViewById(R.id.sales_table);
			TableRow tableRow;
			EditText quantityText;
			for (int i = 1; i < tableLayout.getChildCount(); i++) {
				tableRow = (TableRow) tableLayout.getChildAt(i);
				quantityText = (EditText) tableRow.getChildAt(2);
				if (quantityText.getText().toString().trim().equals("")
						|| Integer.parseInt(quantityText.getText().toString()) < 1) {
					return false;
				}

			}

		} catch (Exception e) {
			logger.logException("isQuantityFilled", e);
		}
		return true;
	}

	private void enableSaveOrder() {
		try {
			TableLayout tableLayout = (TableLayout) findViewById(R.id.sales_table);
			if (tableLayout.getChildCount() < 2) {
				((Button) findViewById(R.id.save_order)).setEnabled(false);
			} else {
				((Button) findViewById(R.id.save_order)).setEnabled(true);
			}

		} catch (Exception e) {
			logger.logException("Check Product Row Exception ", e);
		}
	}

	
	/**
	 * Search Product
	 */
	private void searchProduct() {
		try {

			String skuCategoryName = String.valueOf(skuSpinner
					.getSelectedItem());
			ProductCategroy productCategroy = roverApp
					.getSkuByCategory(skuCategoryName);
			if (productCategroy != null) {
				roverApp.getViewContext().put(
						RoverConstants.CURRENT_SELECTED_SKU, productCategroy);
			} else {
				roverApp.getViewContext().put(
						RoverConstants.CURRENT_SELECTED_SKU, null);
			}
			roverApp.getViewContext()
					.put(RoverConstants.CURRENT_ORDER_BOOKING_LINE,
							orderBookingLine);
			Intent intent = new Intent(this, SearchProductActivity.class);
			startActivityForResult(intent, 1);

		} catch (Exception e) {
			logger.logException("searchProduct", e);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {

			if (resultCode == RoverConstants.CURRENT_ORDER_SUCESS) {

				List<ProductBean> productBeanList = (List<ProductBean>) roverApp
						.getViewContext().get(
								RoverConstants.CURRENT_ORDER_PRODUCT_LIST);
				List<String> quantityList = (List<String>) roverApp
						.getViewContext().get(
								RoverConstants.CURRENT_ORDER_QUANTITY_LIST);
				int i = 0;
				for (ProductBean productBean : productBeanList) {
					if (orderBookingLine.getProductBeanList().contains(
							productBean)) {
						int index = orderBookingLine.getProductBeanList()
								.indexOf(productBean);

						int oldQuantity = Integer.valueOf(orderBookingLine
								.getProductQuantitylist().get(index));
						int newQuantity = Integer.valueOf(quantityList.get(i));
						orderBookingLine.getProductQuantitylist().set(index,
								String.valueOf(newQuantity + oldQuantity));

					} else {
						orderBookingLine.getProductBeanList().add(productBean);
						orderBookingLine.getProductQuantitylist().add(
								quantityList.get(i));
					}

					i++;
				}
				buildProductsTable(orderBookingLine);
			}

		} catch (Exception e) {
			logger.logException("oNActivityResult ", e);
		}

	}

	private void buildProductsTable(OrderBookingLine orderBookingLine) {
		try {

			List<ProductBean> productBeanList = orderBookingLine
					.getProductBeanList();
			List<String> productQuantitylist = orderBookingLine
					.getProductQuantitylist();
			int textColor = getResources().getColor(
					R.color.table_item_text_color);
			int tableItemBg = getResources().getColor(R.color.table_item_bg);
			TableLayout tableLayout = (TableLayout) findViewById(R.id.sales_table);
			if (tableLayout.getChildCount() > 1) {
				tableLayout.removeViews(1, tableLayout.getChildCount() - 1);
			}
			int i = 0;
			double totalPrice = 0.0;
			String quantity;
			for (ProductBean productBean : productBeanList) {
				TableRow orderRow = new TableRow(this);
				orderRow.setTag(productBean);
				quantity = productQuantitylist.get(i++);
				LayoutParams layoutParams = new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
				layoutParams.setMargins(0, 0, 0, 10);

				orderRow.setLayoutParams(layoutParams);
				orderRow.setBackgroundColor(getResources().getColor(
						R.color.table_border_color));

				LayoutParams otherParams = new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
				otherParams.setMargins(1, 0, 0, 1);

				TextView txtSkuName = new TextView(this);
				txtSkuName.setTextAppearance(this, R.style.table_item_font);

				txtSkuName.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtSkuName.setPadding(5, 0, 5, 0);
				txtSkuName.setText(productBean.getDescription());
				txtSkuName.setTextColor(textColor);
				txtSkuName.setBackgroundColor(tableItemBg);
				orderRow.addView(txtSkuName, otherParams);

				TextView txtQty = new TextView(this);
				txtQty.setTextAppearance(this, R.style.table_item_font);
				txtQty.setText(productBean.getUnitPrice());
				txtQty.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtQty.setPadding(5, 0, 5, 0);
				txtQty.setBackgroundColor(tableItemBg);
				txtQty.setTextColor(textColor);

				orderRow.addView(txtQty, otherParams);

				EditText txtDiscount = new EditText(this);
				txtDiscount.setTextAppearance(this, R.style.table_item_font);

				txtDiscount.setTextSize(12.0f);

				txtDiscount.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);

				txtDiscount.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtDiscount.setMinLines(1);
				txtDiscount.setSingleLine();
				txtDiscount.setText(quantity);
				txtDiscount.setHorizontallyScrolling(false);
				txtDiscount.setPadding(5, 0, 5, 0);
				txtDiscount.setTextColor(textColor);
				txtDiscount.setBackgroundColor(tableItemBg);
				txtDiscount.setOnKeyListener(keyListener);
				txtDiscount.setKeyListener(numberKeyListner);

				orderRow.addView(txtDiscount, otherParams);

				totalPrice += Double.valueOf(productBean.getUnitPrice())
						* Integer.parseInt(quantity);

				CheckBox actionButtion = new CheckBox(this);
				actionButtion.setBackgroundColor(getResources().getColor(
						R.color.table_item_bg));
				actionButtion.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				actionButtion.setPadding(2, 0, 2, 0);
				actionButtion.setButtonDrawable(R.drawable.details);
				actionButtion.setOnClickListener(listener);

				orderRow.addView(actionButtion, otherParams);

				tableLayout.addView(orderRow);

			}

			((TextView) findViewById(R.id.total_price)).setText(String
					.valueOf(totalPrice));

			enableSaveOrder();

		} catch (Exception e) {
			logger.logException("buildProductsTable", e);
		}
	}

	private class CheckBoxClickListener implements OnClickListener {
		@Override
		public void onClick(View view) {
			try {
				TableRow tableRow = (TableRow) view.getParent();
				TableLayout tableLayout = (TableLayout) tableRow.getParent();
				int index = orderBookingLine.getProductBeanList().indexOf(
						tableRow.getTag());
				orderBookingLine.getProductQuantitylist().remove(index);
				orderBookingLine.getProductBeanList().remove(tableRow.getTag());
				tableLayout.removeView(tableRow);
				tableLayout.removeView(tableRow);
				enableSaveOrder();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}
